package com.sjd.web.api.user;

import com.sjd.common.core.domain.AjaxResult;
import com.sjd.mall.domain.SjdAccountDO;
import com.sjd.mall.service.account.AccountService;
import com.sjd.wx.domain.SjdMember;
import com.sjd.wx.domain.ThirdSession;
import com.sjd.wx.domain.dto.LoginMaDTO;
import com.sjd.wx.domain.dto.WxOpenDataDTO;
import com.sjd.wx.service.WxUserService;
import com.sjd.wx.utils.ThirdSessionHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * 微信用户
 *
 * @author male
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/wxuser")
public class WxUserApi {

    private final WxUserService wxUserService;
    private final AccountService accountService;

    /**
     * 小程序用户登录
     */
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginMaDTO loginMaDTO) {
        try {
            String appId = wxUserService.getWxMaAppId();
            SjdMember sjdMember = wxUserService.loginMa(appId, loginMaDTO.getJsCode());
            ThirdSession thirdSession = new ThirdSession();
            thirdSession.setAppId(appId);
            thirdSession.setSessionKey(sjdMember.getSessionKey());
            thirdSession.setMemberId(sjdMember.getMemberId());
            thirdSession.setMobile(sjdMember.getPhone());
            thirdSession.setOpenId(sjdMember.getOpenId());
            String thirdSessionKey = UUID.randomUUID().toString();
            thirdSession.setThirdSessionKey(thirdSessionKey);
            SjdAccountDO accountDO = accountService.findAccountByMemberId(sjdMember.getMemberId());
            thirdSession.setAccountId(accountDO.getId());
            wxUserService.updateThirdSession(thirdSession);
            return AjaxResult.success(sjdMember.toMap(thirdSessionKey));
        } catch (Exception e) {
            log.error("小程序登录出现异常，异常信息===>{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping
    public AjaxResult getMemberInfo() {
        Long memberId = ThirdSessionHolder.getSjdMemberId();
        SjdMember sjdMember = wxUserService.getByMemberId(memberId);
        // 将微信的sessionKey留存数据库，redis缓存key返回给小程序前端
        sjdMember.setSessionKey(ThirdSessionHolder.getThirdSession().getThirdSessionKey());
        return AjaxResult.success(sjdMember);
    }

    /**
     * 保存用户信息
     */
    @PostMapping
    public AjaxResult saveOrUpdateWxUser(@Validated @RequestBody WxOpenDataDTO wxOpenDataDTO) {
        return wxUserService.saveOrUpdateWxUser(wxOpenDataDTO);
    }
}
